package com.xwt.web.filter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.xwt.web.jwt.JwtConfigProperty;
import com.xwt.web.jwt.JwtUtil;

/**
 * 登陆成功调用,也可以在这里生成JWT，缺点是过了设置的失效时间必须重新验证
 * 
 * @author Administrator
 *
 */
@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private JwtConfigProperty jwtConfig;
	@Autowired
	private JwtUtil jwtUtil;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		logger.info("登陆成功：" + authentication.getPrincipal().toString());
		String authHeader = request.getHeader(this.jwtConfig.getHeader());
		String tokenHead = this.jwtConfig.getTokenHead();
		if (authHeader == null || "".equals(authHeader)) {
			String username = authentication.getName();
			String token = jwtUtil.generateToken(username);
			response.setHeader(this.jwtConfig.getHeader(), tokenHead + token);
		}
	}

}
